package com.huibao.hulibao.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.huibao.hulibao.R;
import com.huibao.hulibao.adapter.HuliDetailBindMomGvAdapter;
import com.huibao.hulibao.adapter.HuliDetailGvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.BarCodeEntity;
import com.huibao.hulibao.entity.HuLiBindMomEntity;
import com.huibao.hulibao.entity.HuLiRoomEntity;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.ServerEntity;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lizhaoyong on 2018/5/8.
 */
public class ServerDetailActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.tv_server_detail_title)
    TextView tv_server_detail_title;
    @BindView(R.id.tv_sever_detail_room)
    TextView tv_sever_detail_room;

    @BindView(R.id.tv_sever_detail_mom_name)
    TextView tv_sever_detail_mom_name;

    @BindView(R.id.tv_sever_detail_baby)
    TextView tv_sever_detail_baby;

    @BindView(R.id.tv_leixing)
    TextView tv_leixing;

    @BindView(R.id.tv_renwulaiyuan)
    TextView tv_renwulaiyuan;

    @BindView(R.id.tv_fuwurenyuan)
    TextView tv_fuwurenyuan;

    @BindView(R.id.tv_fuwushijian)
    TextView tv_fuwushijian;

    @BindView(R.id.tv_fabushijian)
    TextView tv_fabushijian;

    @BindView(R.id.tv_server_detail_price)
    TextView tv_server_detail_price;

    @BindView(R.id.tv_zhuangtai)
    TextView tv_zhuangtai;

    @BindView(R.id.iv_weiwancheng)
    ImageView iv_weiwancheng;

    @BindView(R.id.tv_kaishirenwu)
    TextView tv_kaishirenwu;

    @BindView(R.id.tv_biaoqianjiaoyan)
    TextView tv_biaoqianjiaoyan;

    @OnClick({R.id.iv_back, R.id.tv_back})
    public void back() {
        onBackPressed();
    }

    private String stime;
    private String status;
    private Dialog myDialog;
    private LoginEntity le;

    @OnClick(R.id.tv_kaishirenwu)
    public void startRenWu() {
        if (sdd == null) {
            return;
        }

        if (sdd.Status.equals(GlobalConstants.STATUS_NO_CONFIRM)) {
            confirmRenwu();
        } else {
            // 处理需要扫码和不需要扫码的逻辑
            if (sdd.ServeStartScanLabel.equals("") && sdd.ServeEndScanLabel.equals("") || status.contains(sdd.TaskId)) {
                stime = MyUtils.getFormatTimeToString(System.currentTimeMillis());
                Intent intent = new Intent(getApplicationContext(), ServerFinishActivity.class);
                intent.putExtra("title", tv_server_detail_title.getText().toString());
                // 结束任务需要用到的参数
                intent.putExtra("TaskId", sdd.TaskId);
                intent.putExtra("stime", stime);
                intent.putExtra("ServerDetailData", sdd);
                startActivity(intent);
            } else {
                Intent intent = new Intent(getApplicationContext(), ScanListActivity.class);
                intent.putExtra("ServerDetailData", sdd);
                startActivity(intent);
            }
        }
    }


    public ServerEntity.ServerDetailData sdd;


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(1101);
    }


    public void confirmRenwu() {
        if (sdd == null) {
            return;
        }
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        myDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("taskid", sdd.TaskId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_CONFIRM_RENWU + object.toString());
        // LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                DialogUtils.closeDialog(myDialog);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    // LogUtils.d("result = " + jsonObject.toString());
                    if(jsonObject.toString().contains("\"State\"" + ":" + "\"" + GlobalConstants.SUCCESS_CODE + "\"")){
                        T.show(getApplicationContext(),"确认成功",0);
                        onBackPressed();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                DialogUtils.closeDialog(myDialog);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                DialogUtils.closeDialog(myDialog);
            }

            @Override
            public void onFinished() {
                DialogUtils.closeDialog(myDialog);
            }
        });

    }

    // 获取二维码
    public void getBarCodeFromServer() {
        if (sdd == null) {
            return;
        }
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        myDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("serveid", sdd.ServeId);
            object.put("roomid", sdd.RoomId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_BARCODE_CHECK + object.toString());
        // LogUtils.d("params = " + params.toString());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                DialogUtils.closeDialog(myDialog);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    BarCodeEntity bce = GlobalConstants.gson.fromJson(jsonObject.toString(), BarCodeEntity.class);
                    if (bce != null && sdd != null) {
                        if (bce.getState().equals(GlobalConstants.SUCCESS_CODE)) {
                            sdd.ServeEndScanLabel = bce.getMessage().getEnd();
                            sdd.ServeStartScanLabel = bce.getMessage().getStart();
                            initData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                DialogUtils.closeDialog(myDialog);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                DialogUtils.closeDialog(myDialog);
            }

            @Override
            public void onFinished() {
                DialogUtils.closeDialog(myDialog);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_detail);
        ButterKnife.bind(this);
        le = (LoginEntity) PreUtils.getObject(getApplicationContext(), "LoginEntity");
        if (le == null) {
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
            finish();
        }

        status = (String) PreUtils.getParam(getApplicationContext(), "RenWuStatus", "");
        sdd = (ServerEntity.ServerDetailData) getIntent().getSerializableExtra("ServerDetailData");
        myDialog = DialogUtils.createLoadingDialog(this, getResources().getString(R.string.jiazaizhong));
        getBarCodeFromServer();

        // 是否显示执行中
        String str = (String) PreUtils.getParam(getApplicationContext(), "RenWuStatus", "");
        if (str.contains(sdd.TaskId)) {
            tv_zhuangtai.setText(R.string.zhixingzhong);
            tv_zhuangtai.setTextColor(getResources().getColor(R.color.text_black));
            iv_weiwancheng.setImageResource(R.mipmap.zhixingzhong);
        } else if (sdd.Status.equals(GlobalConstants.STATUS_NO_CONFIRM)) {
            tv_zhuangtai.setText(R.string.daiqueren);
            iv_weiwancheng.setImageResource(R.mipmap.daiqueren);
            tv_zhuangtai.setTextColor(getResources().getColor(R.color.text_black));
            tv_kaishirenwu.setText(getResources().getString(R.string.querenzhidao));
        }

        initData();

    }

    private void initData() {
        if (sdd != null) {
            tv_fuwushijian.setText(sdd.ServeTime);
            tv_fabushijian.setText(sdd.AddTime);
            tv_sever_detail_room.setText(sdd.RoomName);
            tv_sever_detail_mom_name.setText(sdd.MetherName);
            tv_server_detail_title.setText(sdd.ServeName);
            tv_leixing.setText(sdd.TypeName);
            tv_renwulaiyuan.setText(sdd.ComingName);
            tv_fuwurenyuan.setText(sdd.NurserName);
            tv_server_detail_price.setText("￥" + sdd.ServePrice);

            if (sdd.ServeStartScanLabel.equals("")) {
                tv_biaoqianjiaoyan.setText("不需要");
            } else {
                tv_biaoqianjiaoyan.setText("需要");
            }
        }
    }
}
